package com.atguigu.lease.common.utils;

import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;

import javax.crypto.SecretKey;
import java.util.Date;

public class JwtUtil {

	// 生成一个适合 HMAC-SHA 算法的 SecretKey
	private static SecretKey secretKey = Keys.hmacShaKeyFor("tXZKQJhA26J7BSnwGSh44YZEuaCTja5H".getBytes());

	public static String createToken(Long userId, String username) {
		// 构造器模式
		String jwt = Jwts.builder().
				// setExpiration：设置过期时间
				setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 24 * 365L ))
				// 使用官方字段setSubject：主题
				.setSubject("LOGIN_USER")
				// 用claim设置自定义Payload，用于保存要传递的具体信息
				.claim("userId", userId)
				.claim("username", username)
				.signWith(secretKey, SignatureAlgorithm.HS256)
				.compact();
		return jwt;
	}

	public static Claims parseToken(String token) {

		if (token==null){
			throw new LeaseException(ResultCodeEnum.ADMIN_LOGIN_AUTH);
		}

		try {
			// 得到解析器builder
			JwtParser jwtParser = Jwts.parserBuilder()
					// 放入密钥
					.setSigningKey(secretKey)
					// 得到解析器
					.build();
			// 将payload解析出来，可以从结果获得payload的每个字段
			Jws<Claims> claimsJws = jwtParser.parseClaimsJws(token);
			return claimsJws.getBody();
		} catch (ExpiredJwtException e) {
			throw new LeaseException(ResultCodeEnum.TOKEN_EXPIRED);
		} catch (JwtException e) {
			throw new LeaseException(ResultCodeEnum.TOKEN_INVALID);
		}
	}

	public static void main(String[] args) {
		System.out.println(createToken(1L, "admin"));
	}

}
